package com.onesports.intelligent.k12.polarlight.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.onesports.framework.kit.common.util.BeanUtils;
import com.onesports.framework.kit.common.util.ParamUtils;
import com.onesports.intelligent.k12.polarlight.common.domain.entity.BaseEntity;
import com.onesports.intelligent.k12.polarlight.domain.dto.sys.RunAccountDTO;
import com.onesports.intelligent.k12.polarlight.domain.entity.sys.Account;
import com.onesports.intelligent.k12.polarlight.domain.entity.sys.AccountRole;
import com.onesports.intelligent.k12.polarlight.domain.entity.sys.Role;
import com.onesports.intelligent.k12.polarlight.domain.vo.sys.RunAccountVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Wsy
 **/
@Service
@RequiredArgsConstructor
public class RunAccountService {

    private final AccountService accountService;
    private final AccountRoleService accountRoleService;
    private final RoleService roleService;

    /**
     * 添加运营账号
     *
     * @param dto 入参
     */
    @Transactional(rollbackFor = Exception.class)
    public Account add(RunAccountDTO dto, String organizationId) {
        //校验账号
        this.accountService.checkExist(dto.getPhone(),organizationId, dto.getId(), null);
        //添加账号
        Account account = BeanUtils.copyProperties(dto, Account.class);
        account.setOrganizationId(organizationId);
        this.accountService.add(account);
        //添加账号角色
        if(CollectionUtils.isNotEmpty(dto.getRoleIds())){
            this.accountRoleService.addAccountRole(dto.getRoleIds(), account.getId());
        }
        return account;
    }

    /**
     * 编辑运营账号
     *
     * @param dto 运营账号入参
     */
    @Transactional(rollbackFor = Exception.class)
    public void edit(RunAccountDTO dto) {
        //校验账号
        this.accountService.checkExist(dto.getPhone(),dto.getOrganizationId(), dto.getId(), null);
        Account account = BeanUtils.copyProperties(dto, Account.class, "password");
        this.accountService.update(account);
        //修改账号角色
        if(CollectionUtils.isNotEmpty(dto.getRoleIds())){
            this.editAccountRole(dto.getId(), dto.getRoleIds());
        }
    }


    /**
     * 修改账号角色
     *
     * @param id      账号id
     * @param roleIds 角色ids
     */
    private void editAccountRole(String id, List<String> roleIds) {
        this.accountRoleService.deleteByAccountId(id);
        this.accountRoleService.addAccountRole(roleIds, id);
    }


    /**
     * 删除账号
     *
     * @param accountId 账号id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String accountId) {
        this.accountService.removeById(accountId);
        this.accountRoleService.deleteByAccountId(accountId);
    }


    /**
     * 分页查询运营账号
     *
     * @param page     分页参数
     * @param phone    手机账号
     * @param username 姓名
     * @return PageResult<RunAccountVO>
     */
    public IPage<RunAccountVO> page(Page<Account> page, String phone, String username, Boolean status, String gender, String organizationId) {

        //分页查询
        IPage<Account> iPage = this.accountService.page(page, phone, username, status, gender, Collections.singletonList(organizationId));
        List<Account> records = iPage.getRecords();
        IPage<RunAccountVO> returnPage = iPage.convert(account -> BeanUtils.copyProperties(account, RunAccountVO.class));
        if (ParamUtils.isEmpty(records)) {
            return returnPage;
        }
        List<String> accountIds = records.stream().map(Account::getId).collect(Collectors.toList());
        //获取所有运营角色(key:id val:roleName)
        Map<String, Role> roleMap = this.roleService.selectRoleMap(organizationId);
        //获取账号角色
        Map<String, List<AccountRole>> accountRoleMap = this.accountRoleService.list(new QueryWrapper<AccountRole>().lambda()
                .in(AccountRole::getAccountId, accountIds)).stream().collect(Collectors.groupingBy(AccountRole::getAccountId));

        returnPage.getRecords().forEach(runAccount -> {
            runAccount.setIsSuper(false);
            if (MapUtils.isNotEmpty(accountRoleMap)&&CollectionUtils.isNotEmpty(accountRoleMap.get(runAccount.getId()))) {

                List<Role> roles = accountRoleMap.get(runAccount.getId()).stream().map(i -> {
                    Role role = new Role();
                    role.setId(i.getRoleId());
                    if (roleMap != null) {
                        Role runRole = roleMap.get(i.getRoleId());
                        role.setRoleName(runRole != null ? runRole.getRoleName() : "");
                        role.setIsSuper(runRole != null ? runRole.getIsSuper() : false);
                    }
                    return role;
                }).collect(Collectors.toList());
                List<Role> superRole = roles.stream().filter(f -> f.getIsSuper().equals(Boolean.TRUE)).collect(Collectors.toList());
                if (ParamUtils.isNotEmpty(superRole)) {
                    runAccount.setIsSuper(true);
                }
                runAccount.setRoles(roles);
            }
        });


        List<RunAccountVO> results = returnPage.getRecords();
        List<RunAccountVO> finishResults = results.stream().filter(f -> f.getIsSuper().equals(Boolean.FALSE)).collect(Collectors.toList());
        returnPage.setRecords(finishResults);
        return returnPage;
    }
}
